package org.mic.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.mic.filter.request.BodyReaderHttpServletRequestWrapper;
import org.mic.filter.request.HttpHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by luoxiaofei on 2017/4/25.
 */
@Component
public class PreServerFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(PreServerFilter.class);

    private final static String type = "pre";

    //private final static String appId = "4";

    @Value("${zuul.open}")
    private boolean open;

    @Override
    public String filterType() {
        return type;
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return open && (boolean) ctx.get("isSuccess");
    }

    @Override
    public Object run() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        RequestContext ctx = RequestContext.getCurrentContext();
        //ctx.addZuulRequestHeader(UserConfig.APP_ID_KEY, appId);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        ctx.set("isSuccess", false); //是否往下传递验证

        String path = request.getServletPath();

        if (isSysPath(ctx, path)) return null;

        boolean mark = false;
        if (path.contains("/u/")) {
            String uId = null;
            if (path.contains("/api/v")) {
                uId = getRequestUserId(request);
            }
            if (!checkCurUser(uId)) {
                ctx.setResponseStatusCode(200);// 返回错误码
                ctx.setSendZuulResponse(false);// 过滤该请求，不对其进行路由
                ctx.setResponseBody("{\"result\": -2, \"msg\": \"未授权，请登录\"}");// 返回错误内容
            }
        }

        long endTime = System.currentTimeMillis();
        //logger.info(String.format("request method '%s', run time '%s', path:%s", request.getMethod(), (endTime - startTime), path));
        return null;
    }

    private boolean isSysPath(RequestContext ctx, String path) {
        if (path.contains("/i/")) {
            ctx.setResponseStatusCode(404);// 返回错误码
            ctx.setSendZuulResponse(false);// 过滤该请求，不对其进行路由
            ctx.setResponseBody("{\"result\": -1, \"msg\": \"地址不存在\"}");
            return true;
        }
        return false;
    }

    /**
     * 检查登录
     */
    private boolean checkLogin() {
        boolean result = false;
        return result;
    }

    private boolean checkCurUser(String userId) {
        boolean result = false;
        return result;
    }

    private String getRequestUserId(HttpServletRequest request) {
        String userId = null;
        if (request.getMethod().equalsIgnoreCase("get") || request.getMethod().equalsIgnoreCase("delete")) {
            userId = request.getParameter("userId");
            if (userId == null) {
                userId = getPathUserId(request);
            }
        } else if (request.getMethod().equalsIgnoreCase("post") || request.getMethod().equalsIgnoreCase("put")) {
            BodyReaderHttpServletRequestWrapper requestWrapper = null;
            try {
                requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String bodyStr = HttpHelper.getBodyString(requestWrapper);

            try {
                //JSONObject bodyJSON = JSONObject.parseObject(bodyStr);
                //userId = bodyJSON.get("userId").toString();
            } catch (Exception e) {
                //logger.error("获取userId异常, path：" + request.getServletPath());
            }
        }
        return userId;
    }

    private String getPathUserId(HttpServletRequest request) {
        String userId = null;
        try {
            String path = request.getServletPath();
            int lastIndexOf = path.lastIndexOf('/');
            userId = path.substring(lastIndexOf + 1);
            if (!StringUtils.isNumeric(userId))
                userId = null;

            //logger.info("path indexOf userId:" + userId);
        } catch (Exception e) {
        }
        return userId;
    }

}
